//
//  WDLoanEditCell.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2017/2/12.
//  Copyright © 2017年 王笛. All rights reserved.
//

#import "WDLoanEditCell.h"
#import "WDMaterialDetail.h"
#import "WDData.h"
#import "BDImagePicker.h"
#import "LGPhoto.h"
#import "WDUploadData.h"
#import "WDEditImageCell.h"

#define HEADER_HEIGHT 100
#define cellItemW ([UIScreen mainScreen].bounds.size.width - 80) / 2
#define cellItemH 102

NSString *const WDUploadStatusNotificaton = @"WDUploadStatusNotificaton";

typedef void (^uploadFinish)(id result);

typedef void (^uploadError)(id result);

@interface WDLoanEditCell ()<LGPhotoPickerViewControllerDelegate, UIActionSheetDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UICollectionViewDelegate, UICollectionViewDataSource>
/** 左边圆点 */
@property (nonatomic, strong) UIImageView *pointView;
/** 左边线 */
@property (nonatomic, strong) UIImageView *lineView;
/** 标题 */
@property (nonatomic, strong) UILabel *titleLabel;
/** collectionView */
@property (nonatomic, strong) UICollectionView *collectionView;
/** 图片显示类型 */
@property (nonatomic, assign) LGShowImageType showType;
/** 用来存放cell的唯一标示 */
@property (nonatomic, strong) NSMutableDictionary *cellDict;

@end

static NSString *cellID = @"imageCell";

@implementation WDLoanEditCell

//懒加载collectionView
- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        
        //滚动方向（竖直方向）
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 10;
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
        
        _collectionView.scrollEnabled = NO;
        
        _collectionView.delegate = self;
        
        _collectionView.dataSource = self;
        
        _collectionView.backgroundColor = [UIColor clearColor];
        
        [self.contentView addSubview:_collectionView];
        
    }
    
    return _collectionView;
}

+ (instancetype)loanEditCellWithTableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"loanEditCell";
    
    NSString *identifier = [NSString stringWithFormat:@"%@%zd%zd", cellID, indexPath.section, indexPath.row];
    
    WDLoanEditCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (!cell) {
        cell = [[WDLoanEditCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    return cell;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        self.cellDict = [NSMutableDictionary dictionary];
        
        //拍摄资料列表
        UIImageView *pointView = [[UIImageView alloc] init];
        
        [pointView sizeToFit];
        
        [self.contentView addSubview:pointView];
        self.pointView = pointView;
        if (self.isFirstCell) {
            [pointView makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(10);
                make.top.equalTo(23);
                
            }];
        } else {
            [pointView makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(10);
                make.top.equalTo(0);
                
            }];
        }
        
        [pointView layoutIfNeeded];
        
        
        UIImageView *lineView = [[UIImageView alloc] init];
        lineView.image = [UIImage imageNamed:@"single_line"];
        [self.contentView addSubview:lineView];
        self.lineView = lineView;
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.textColor = ColorForRGB(0x6b6b6b);
        titleLabel.font = [UIFont systemFontOfSize:14];
        titleLabel.textAlignment = NSTextAlignmentLeft;
        [self.contentView addSubview:titleLabel];
        self.titleLabel = titleLabel;
        [titleLabel makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(pointView.right).offset(0);
            make.centerY.equalTo(pointView.centerY);
        }];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notif:) name:WDUploadStatusNotificaton object:nil];
        
    }
    return self;
}

- (void)setMaterialDetail:(WDMaterialDetail *)materialDetail
{
    _materialDetail = materialDetail;
    self.titleLabel.text = materialDetail.name;
    
    [self.lineView makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(10);
        make.top.equalTo(self.pointView.bottom);
        make.bottom.equalTo(self.contentView.bottom);
    }];
}

- (void)setImagesData:(NSArray *)imagesData
{
    _imagesData = (NSMutableArray *)imagesData;
    
    self.collectionView.frame = CGRectMake(35, 30, SCREEN_WIDTH - 70, self.materialDetail.DetailCellH + 20);
    
    //刷新collectionView
    [self.collectionView reloadData];
}

- (void)setFirstCell:(BOOL)firstCell
{
    _firstCell = firstCell;
    if (firstCell && self.lastCell) {
        self.pointView.image = [UIImage imageNamed:@"redPoint"];
        self.lineView.hidden = NO;
    } else if (firstCell) {
        self.pointView.image = [UIImage imageNamed:@"first_red"];
        self.lineView.hidden = NO;
    } else if (self.isLastCell){
        self.pointView.image = [UIImage imageNamed:@"last_red"];
        self.lineView.hidden = YES;
    } else {
        self.pointView.image = [UIImage imageNamed:@"middle_red"];
        self.lineView.hidden = NO;
    }
    
}

- (void)setLastCell:(BOOL)lastCell
{
    _lastCell = lastCell;
    if (self.firstCell && lastCell) {
        self.pointView.image = [UIImage imageNamed:@"redPoint"];
        self.lineView.hidden = NO;
    } else if (lastCell) {
        self.pointView.image = [UIImage imageNamed:@"last_red"];
        self.lineView.hidden = YES;
    } else if (self.isFirstCell){
        self.pointView.image = [UIImage imageNamed:@"first_red"];
        self.lineView.hidden = NO;
    } else {
        self.pointView.image = [UIImage imageNamed:@"middle_red"];
        self.lineView.hidden = NO;
    }
}

#pragma mark - 接受通知
- (void)notif:(NSNotification *)notif
{
    WDSQLiteManager *manager = [WDSQLiteManager manager];
    self.imagesData = (NSMutableArray *)[manager selectWithTable:NSStringFromClass([WDUploadData class]) whereCondition:@{@"imageType":self.materialDetail.id}];
    
    [self.collectionView reloadData];
    
    [_delegate reloadDataTableView:_index collectionView:0];
}


//跳转控制器
- (void)presentPhotoPickerViewControllerWithStyle:(LGShowImageType)style
{
    // 创建控制器
    LGPhotoPickerViewController *pickerVc = [[LGPhotoPickerViewController alloc] initWithShowType:style];
    // 默认显示相册里面的内容SavePhotos
    pickerVc.status = PickerViewShowStatusCameraRoll;
    // 最多能选20张图片
    pickerVc.maxCount = 20;
    pickerVc.delegate = self;
    self.showType = style;
    [pickerVc showPickerVc:_delegate];
}

#pragma mark - 上传图片方法
- (void)uploadImage
{
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"uploadRunning"];
    
    WDSQLiteManager *manager = [WDSQLiteManager manager];
    
    NSArray *uploadImages = [manager selectWithTable:NSStringFromClass([WDUploadData class])whereCondition:@{@"status":@(UploadStatusWaiting)}];
    //判断数据库是否等于0
    if (uploadImages.count == 0) {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"uploadRunning"];
        return ;
    }
    
    WDUploadData *uploadData = uploadImages[0];
    
    UIImage *uploadImage = [UIImage imageWithContentsOfFile:[WDCachePath stringByAppendingPathComponent:uploadData.imagePath]];
    NSData *imageData = UIImageJPEGRepresentation(uploadImage, 1.0);
    
    //上传操作
    [self uploadRequest:imageData fileName:uploadData.imageName uploadFinish:^(id result) {
        
        //成功状态
        NSDictionary *keyValues = @{
                                    @"status":@(UploadStatusFinish),
                                    @"objectId":result[@"file_id"]
                                    };
        
        NSDictionary *condition = @{
                                    @"imagePath":uploadData.imagePath
                                    };
        
        [manager updateWithTable:NSStringFromClass([WDUploadData class]) setKeyValues:keyValues whereCondition:condition];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:WDUploadStatusNotificaton object:nil];
        
        [self uploadImage];
        
    } uploadError:^(id result) {
        
        //失败状态
        [manager updateWithTable:NSStringFromClass([WDUploadData class]) setKeyValues:@{@"status":@(UploadStatusError)} whereCondition:@{@"imageName":uploadData.imagePath}];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:WDUploadStatusNotificaton object:nil];
        
        [self uploadImage];
        
    }];
    
}

- (void)uploadRequest:(NSData *)imageData fileName:(NSString *)fileName uploadFinish:(uploadFinish)uploadFinish uploadError:(uploadError)uploadError
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLogin]];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    NSDictionary *parameters = @{
                                 @"finance_id":self.financeID,
                                 @"file_type":self.materialDetail.id,
                                 @"file_name":fileName,
                                 @"material_type":@1,
                                 @"ctype":@3
                                 };
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLFinanceFileUpLoad];
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //上传图片
        // 可以在上传时使用当前的系统时间作为文件名
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
        
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //上传成功，修改状态
        uploadFinish(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //上传失败，修改状态
        uploadError(error);
    }];
}

#pragma mark - <UICollectionView代理>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.imagesData.count == 0) {
        
        return 1;
        
    } else {
        
        return self.imagesData.count + 1;
        
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identifier = [_cellDict objectForKey:[NSString stringWithFormat:@"%@", indexPath]];
    // 如果取出的唯一标示符不存在，则初始化唯一标示符，并将其存入字典中，对应唯一标示符注册Cell
    if (identifier == nil) {
        identifier = [NSString stringWithFormat:@"%@%@", cellID, [NSString stringWithFormat:@"%@", indexPath]];
        [_cellDict setValue:identifier forKey:[NSString stringWithFormat:@"%@", indexPath]];
        // 注册Cell
        UINib *nib = [UINib nibWithNibName:NSStringFromClass([WDEditImageCell class]) bundle:nil];
        [self.collectionView registerNib:nib forCellWithReuseIdentifier:identifier];
    }
    
    WDEditImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    
    cell.isShowBtn = self.isEditMode;
    
    if (indexPath.row < self.imagesData.count) {
        cell.addImage = NO;
        WDUploadData *uploadData = self.imagesData[indexPath.row];
        cell.uploadStatus = (NSInteger)uploadData.status;
        cell.uploadData = uploadData;
    } else {
        //设置添加图片
        cell.addImage = YES;
        
    }
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake(cellItemW, cellItemH);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row < self.imagesData.count) {
        
        if (!self.isEditMode) {//编辑模式，点击改变按钮的选中与否
            
            NSMutableArray *images = [NSMutableArray array];
            WDUploadData *uplaodData;
            NSString *imageURL;
            for (uplaodData in self.imagesData) {
                
                if (uplaodData.imagePath) {
                    
                    imageURL = uplaodData.imagePath;
                } else {
                    imageURL = uplaodData.url;
                }
                [images addObject:imageURL];
            }
            
            [_delegate loanEditShowOriginalImage:images clickIndex:indexPath.row];
            
        } else {
            
            WDEditImageCell *cell = (WDEditImageCell *)[collectionView cellForItemAtIndexPath:indexPath];
            
            cell.isSelectedBtn = YES;
        }
        
    } else {//添加图片
        
        if (!self.isEditMode) {
            
            UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"请选择上传方式" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册选取", nil];
            
            UIView *window = [UIApplication sharedApplication].keyWindow;
            [sheet showInView:window];
        }
    }
}



#pragma mark - <UIActionSheetDelegate>
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *title = [actionSheet buttonTitleAtIndex:buttonIndex];
    if ([title isEqualToString:@"拍照"]) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            if ([self isCanUsePhotos]) {
                
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                picker.delegate = self;
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                [_delegate presentViewController:picker animated:YES completion:nil];
            } else {
                
                [_delegate showAlertWithMessage:@"请为致汇金服开放相册权限：手机设置->隐私->相机->致汇金服（打开）"];
            }
            
        } else {
            [_delegate showAlertWithMessage:@"相机不可用"];
        }
        
    }else if ([title isEqualToString:@"从相册选取"]) {
        
        if ([self isCanUsePhotos]) {
            
            [self presentPhotoPickerViewControllerWithStyle:LGShowImageTypeImagePicker];
        } else {
            
            [_delegate showAlertWithMessage:@"请为致汇金服开放相册权限：手机设置->隐私->相册->致汇金服（打开）"];
        }
        
    }else {
        
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *pickerImage = info[@"UIImagePickerControllerOriginalImage"];
    
    //把图片加入到数据库中
    //创建数据库
    WDSQLiteManager *manager = [WDSQLiteManager manager];
    [manager creatTable:NSStringFromClass([WDUploadData class]) WithPrimaryKey:nil];
    
    //把图片存进沙盒
    
    NSString* str = [NSString stringWithFormat:@"%zd", [[NSDate date] timeIntervalSince1970]];
    
    NSString *imagePath = [WDCachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg", str]];
    
    [UIImageJPEGRepresentation(pickerImage, 1.0) writeToFile:imagePath atomically:YES];
    WDUploadData *data = [[WDUploadData alloc] init];
    
    data.financeId = self.financeID;
    data.supplierId = self.supplierId;
    data.status = UploadStatusWaiting;
    data.imageType = [self.materialDetail.id integerValue];
    data.imageTypeName = self.materialDetail.name;
    data.imagePath = [NSString stringWithFormat:@"%@.jpg", str];
    data.imageName = [NSString stringWithFormat:@"%@.jpg", self.materialDetail.name];
    data.fileSize = [NSString stringWithFormat:@"%zd", [UIImageJPEGRepresentation(pickerImage, 1.0) length] / 1000.0];
    data.mimeType = @"image/jpeg";
    data.materialType = @"1";
    
    //插入数据库
    [manager insertWithTable:NSStringFromClass([WDUploadData class]) andModel:data];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    [_delegate reloadDataTableView:self.index collectionView:self.imagesData.count];
    
    //读数据
    self.imagesData = (NSMutableArray *)[manager selectWithTable:NSStringFromClass([WDUploadData class]) whereCondition:@{@"imageType":@([self.materialDetail.id integerValue])}];
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"uploadRunning"]) {
        return;
    } else {
        [self uploadImage];
    }
    
}

//判断相机相册是否有权限
- (BOOL)isCanUsePhotos {
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
        ALAuthorizationStatus author =[ALAssetsLibrary authorizationStatus];
        if (author == kCLAuthorizationStatusRestricted || author == kCLAuthorizationStatusDenied) {
            //无权限
            return NO;
        }
    }
    else {
        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
        if (status == PHAuthorizationStatusRestricted ||
            status == PHAuthorizationStatusDenied) {
            //无权限
            return NO;
        }
    }
    return YES;
}

#pragma mark - <LGPhotoPickerViewControllerDelegate>
- (void)pickerViewControllerDoneAsstes:(NSArray *)assets isOriginal:(BOOL)original
{
    
    LGPhotoAssets *temp = nil;
    WDUploadData *data = [[WDUploadData alloc] init];
    
    //数据库操作
    WDSQLiteManager *manager = [WDSQLiteManager manager];
    [manager creatTable:NSStringFromClass([WDUploadData class]) WithPrimaryKey:nil];
    
    for (temp in assets) {
        //把图片存进沙盒
        static NSInteger i = 0;
        
        NSString* str = [NSString stringWithFormat:@"%zd%zd", [[NSDate date] timeIntervalSince1970], i];
        
        i++;
        
        NSString *imagePath = [WDCachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg", str]];
        
        [UIImageJPEGRepresentation(temp.originImage, 1.0) writeToFile:imagePath atomically:YES];
        
        //前1000是网络图片 1000+是本地图片
        data.financeId = self.financeID;
        data.supplierId = self.supplierId;
        data.status = UploadStatusWaiting;
        data.imageType = [self.materialDetail.id integerValue];
        data.imageTypeName = self.materialDetail.name;
        data.imageName = [NSString stringWithFormat:@"%@.jpg", self.materialDetail.name];
        data.fileSize = [NSString stringWithFormat:@"%zd", temp.originImageSize];
        data.imagePath = [NSString stringWithFormat:@"%@.jpg", str];
        WDLog(@"%@", data.imagePath);
        data.mimeType = @"image/jpeg";
        data.materialType = @"1";
        
        [manager insertWithTable:NSStringFromClass([WDUploadData class]) andModel:data];
    }
    
    [_delegate reloadDataTableView:self.index collectionView:self.imagesData.count];
    
    //WDLog(@"%@", NSHomeDirectory());
    
    self.imagesData = (NSMutableArray *)[manager selectWithTable:NSStringFromClass([WDUploadData class]) whereCondition:@{@"imageType":@([self.materialDetail.id integerValue])}];
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"uploadRunning"]) {
        return;
    } else {
        [self uploadImage];
    }
}

@end
